<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <template id="tpl">
        {% if(sex) { %}
            <div>男</div>
        {% } else { %}
            <div>女</div>
        {% } %}    
    </template>
    <!-- 将上述模板转为如下 -->
    <template id="tpl">
        str+=`
        ` if(sex) { str+=`
            <div>男</div>
        ` } else { str+=`
            <div>女</div>
        ` } str+=`
        `
    </template>
    <script>
        const fn = new Function('console.log(12)');
        console.log(fn.toString())
        // 上述结果： 一个匿名函数的函数体，是'console.log(12)'
        // function anonymous() {
        //     console.log(12)
        // }
        const tpl1 = new Function('data', 'console.log(data.name)');
        console.log(tpl1.toString())
        // 上述结果
        // function anonymous(data) {
        //     console.log(`${data.name}`)
        // }
        console.log(tpl1({ name: 'ck' }))

        const tpl2 = new Function('data', 'console.log("你的名字:"+data.name)');
        console.log(tpl2.toString())
        console.log(tpl2({ name: 'ck' }))

        const tpl3 = new Function('data', 'return `<div>${data.name}</div>`');
        console.log(tpl3.toString());
        console.log(tpl3({name: 'ck'}));

        const tpl4 = new Function('data', 'with(data){ return `<div>${name}</div>` }');
        console.log(tpl4.toString());
        console.log(tpl4({name: 'ck'}));

        const tpl = '<div class="cls">你的姓名：${name}</div>';
        const tpl5 = new Function('data', 'with(data){ return `'+tpl+'` }');
        console.log(tpl5.toString());
        console.log(tpl5({name: '陈康'}));


        // 请看上面的<template>和思路
        const htmlTpl = document.querySelector('#tpl').innerHTML;
        function compile(tpl) {
            return tpl.replace(/(\{%|%\})/g, (...args) => {
                return args[1] === '{%' ? '`;' : 'str+=`';
            });
            // 去掉没用的空白符
            //.replace(/\s*(`)\s*/g, '$1');
        }
        console.log(compile(htmlTpl));
        const tpl6 = new Function('data', 'let str=""; with(data){ str+=`'+compile(htmlTpl)+'`; return str; }');
        console.log(tpl6.toString());
        console.log(tpl6({ sex: 1}));
    </script>
</body>
</html>